package com.qsmx.qingqiuticket.app.util;

import android.content.Context;
import android.os.Environment;

import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;

import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;

public class LogUtils {

    /**
     * 保存错误信息到文件中
     *
     * @return 返回文件名称, 便于将文件传送到服务器
     * isFirstOrEnd : 0 1(开始) 2（结束）
     */
    public static String saveLog2File(String type, boolean isStart) {
        StringBuffer sb = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String time = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        if (isStart) {
            sb.append("************************************************" + time + "****************************************" + "\r\n");
            sb.append("\r\n");
        }
        sb.append(type);
        sb.append("\r\n");
//        String statsStr = "卡机设备状态：" + AtmosPreference.getCustomStringPre(FusionPre.DEVICE_STATUS) + "\n" +
//                "卡机通道状态：" + AtmosPreference.getCustomStringPre(FusionPre.TUNNEL_STATUS) + "\n" +
//                "发卡箱状态：" + AtmosPreference.getCustomStringPre(FusionPre.STACK_STATUS) + "\n" +
//                "回收箱状态：" + AtmosPreference.getCustomStringPre(FusionPre.RECYCLE_STATUS) + "\n" +
//                "卡机是否在线：" + AtmosPreference.getCustomStringPre(FusionPre.IS_ONLINE);
//        sb.append(statsStr);

        if (!isStart) {
            sb.append("\r\n");
            sb.append("************************************************" + time + "****************************************" + "\r\n");
        }
        try {
            String fileName = "Log-" + StringUtil.getDateToStringToday(System.currentTimeMillis()) + ".txt";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = FusionCode.SAVE_PATH + "Log";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(path + File.separator + fileName);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fileWriter = new FileWriter(file, true);
                fileWriter.write(sb.toString());
                fileWriter.close();
            }
            return fileName;
        } catch (Exception e) {
            return null;
        }
    }
}
